<template>
  <ul class="spgcart_ul">
  <li class="spgcart_li" v-for="(item,index) in items" :key='item.name' v-show="!items[index].sum==0">
        <div class="icons"><span class="iconfont" :class='{"active":active}' @click="activeR" :data-index='index'>&#xe8bd;</span></div>

        <div class="pgcart_li_centent">
            <img :src="item.imgUrl" alt="">
            <div class="pgcart_li_centent_text">
                <p class="title">{{item.name}}</p>
                <p><span class="price">{{item.price}}</span><span class="price_r">{{item.oldPrice}}</span></p>
            </div>
        </div>

        <div class="spgcart_li_add">
           <span class="iconfont rde" @click="red" :data-d='index'>&#xe8b1;</span>
          <span class="num">{{shoppingCartSum(item._id,item.shopId)}}</span>
           <span class="iconfont add" @click="add" :data-d='index'>&#xe728;</span>
        </div>
    </li>
  </ul>
</template>

<script>
import { ref } from '@vue/reactivity'
import { bus } from '../../assets/js/public.js'

const items = ref([])
const sums = ref([])
let removeArr = []
export default {
  name: 'Spgcart',
  props: ['active'],
  setup (props, center) {
    // 数据初始化
    init()
    // 购物车加
    function add (e) {
      addRed(e, true)
    }
    // 购物车减
    function red (e) {
      addRed(e)
    }
    // 删除和全选
    removeAll()

    function activeR (e) {
      atc(e)
    }
    return { items, sums, add, red, shoppingCartSum, activeR }
  }
}

// 数据初始化实现逻辑
function init () {
  items.value = []
  for (const i in localStorage) {
    if (i.includes('ls')) {
      const item = JSON.parse(localStorage[i])
      items.value = items.value.concat(item)
    }
  }
}

// 购物车加减函数封装
function addRed (e, isAdd) {
  const d = e.target.dataset.d
  const id = items.value[d]._id
  const shopId = items.value[d].shopId
  let sum = 0
  let index = 0
  if (items.value.length !== 0) {
    for (let i = 0; i < items.value.length; i++) {
      if (items.value[i]._id === id && items.value[i].shopId === shopId) {
        index = i
        // eslint-disable-next-line no-unused-expressions
        isAdd ? (items.value[i].sum++, sum = items.value[i].sum) : (items.value[i].sum--, sum = items.value[i].sum)
      }
    }
  }
  storage(id, shopId, sum)
  bus.emit('busSum', { id, shopId, sum })
  bus.emit('busSpgcart', {
    spgCart: isAdd ? 1 : -1,
    price: isAdd ? items.value[index].price : -items.value[index].price
  })
}

// 通过商店id和商品id进行分类存储
function storage (id, shopId, sum) {
  const arr = JSON.parse(localStorage.getItem(`ls${shopId}`))
  for (var i = 0; i < arr.length; i++) {
    if (arr[i]._id === id) {
      arr[i].sum = sum
      break
    }
  }
  // eslint-disable-next-line no-unused-expressions
  arr[i].sum === 0 ? arr.splice(i, 1) : null
  arr.length === 0 ? localStorage.removeItem(`ls${shopId}`) : localStorage.setItem(`ls${shopId}`, JSON.stringify(arr))
}

// 此函数被DOM插值表达式直接引用，dom节点使用了循环，所以此函数不要和其它函数封装，避免多次执行
function shoppingCartSum (id, shopId) {
  if (items.value.length !== 0) {
    for (let i = 0; i < items.value.length; i++) {
      if (items.value[i]._id === id && items.value[i].shopId === shopId) {
        return items.value[i].sum
      }
    }
  }
  return 0
}

// 删除和全选逻辑
function removeAll () {
  bus.off('remove')
  bus.on('remove', () => {
    let sum = 0
    let price = 0
    for (const i of removeArr) {
      sum = sum + i.sum
      price = price + i.sum * i.price
      bus.emit('busSum', { id: i._id, shopId: i.shopId, sum: 0 })
      items.value[i.index].sum = 0
      const arr = JSON.parse(localStorage.getItem(`ls${i.shopId}`))
      if (arr) {
        for (var k = 0; k < arr.length; k++) {
          if (arr[k]._id === i._id) {
            arr.splice(k, 1)
          }
        }
        arr.length === 0 ? localStorage.removeItem(`ls${i.shopId}`) : localStorage.setItem(`ls${i.shopId}`, JSON.stringify(arr))
      }
    }
    bus.emit('busSpgcart', {
      spgCart: -sum,
      price: -price
    })
    removeArr = []
  })

  bus.off('removeAll')
  bus.on('removeAll', (active) => {
    if (active) {
      removeArr = []
      for (const [index, value] of items.value.entries()) {
        value.index = index
        removeArr.push(value)
      }
    }
  })
}

// 购物车对勾逻辑
function atc (e) {
  const d = e.target.dataset.index
  const id = items.value[d]._id
  const shopId = items.value[d].shopId
  if (e.target.classList.contains('active')) {
    e.target.classList.remove('active')
    removeArr.splice(isId(id, shopId), 1)
    bus.emit('removeAllActive')
  } else {
    e.target.classList.add('active')
    removeArr.push(items.value[d])
    removeArr[removeArr.length - 1].index = d
  }
}

// 通过id返回对应的下标
function isId (id, shopId) {
  for (const [index, value] of removeArr.entries()) {
    if (value._id === id && value.shopId === shopId) {
      return index
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../assets/style/public.scss';
.spgcart_ul{
    margin-top: 16px;
    max-height: 200px;
    overflow-y: auto;
}
.spgcart_li{
    display: flex;
    margin-bottom: .16rem;
    position: relative;
    .icons{
        margin-right: .164rem;
        .iconfont{
        font-size: .2rem;
        line-height: .46rem;
        color: #666666;
        }
         .active{
        color: #0091FF ;
    }

    }
    img{
        width: .46rem;
        height: .46rem;
    }
}
.pgcart_li_centent{
    font-size: .14rem;
    display: flex;
    p{margin: 0;}
   overflow: hidden;
}
.pgcart_li_centent_text{
    margin-left: .16rem;
    overflow: hidden;
    .title{
        font-weight: bold;
        margin-bottom: .12rem;
        @include text-ellipsis(auto);
    }
    .price{
        color: #E93B3B;
    }
    .price_r{
        display: inline-block;
        color: #999999;
        margin-left: .12rem;
        transform: scale(0.8);
        text-decoration: line-through;
    }
}
.spgcart_li_add{
    position: absolute;
    top: .14rem;
    right: 0;
    .iconfont{
        font-size: .2rem;
    }
    .num{
        font-size: .14rem;
        margin: 0 .16rem;
    }
    .rde{
        color: #666666;
    }
     .add{
        color: #0091FF ;
    }
}
.none{
    display: none;
}
</style>
